import cantools
import can
import threading
import time

def is_can_fd(dbc_file):
  can_fd = False
  db = cantools.database.load_file(dbc_file)
  for db_message in db.messages:
    if db_message.length > 8:  # 如果任何消息长度大于8字节，那么假定这是CAN FD协议
      can_fd = True
      break
  return can_fd

# CAN接收函数
def can_receiver(can_bus, bus_name):
  while True:
    message = can_bus.recv(10.0)
    if message:
      print(f"Received on {bus_name}: {message}")

# CAN发送函数
def can_sender(can_bus, bus_name, message):
  while True:
    can_bus.send(message)
    print(f"Sent on {bus_name}: {message}")
    time.sleep(1)  # 发送消息的间隔时间

def create_bus(channel, bustype='socketcan'):
  return can.interface.Bus(channel=channel, bustype=bustype)

def main():
  # 初始化多个CAN总线
  buses = {
    'can0': create_bus('can0'),
    'can1': create_bus('can1')
    # 可以根据需要添加更多的总线
  }

  # 创建并启动接收和发送线程
  threads = []
  for bus_name, can_bus in buses.items():
    # 创建并启动接收线程
    receiver_thread = threading.Thread(target=can_receiver, args=(can_bus, bus_name), daemon=True)
    receiver_thread.start()
    threads.append(receiver_thread)

    # 创建一个要发送的消息对象
    message = can.Message(arbitration_id=0x123, data=[0x11, 0x22, 0x33], is_extended_id=False)

    # 创建并启动发送线程
    sender_thread = threading.Thread(target=can_sender, args=(can_bus, bus_name, message), daemon=True)
    sender_thread.start()
    threads.append(sender_thread)

  # 等待所有线程结束（这里不会发生，因为我们使用了守护线程）
  for thread in threads:
    thread.join()

if __name__ == "__main__":
  main()
